package com.srd.phone.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.shengrongdai.srd.R;

import java.util.Random;

/**
 * 验证码的dialog
 */
public class DialogVerificationActivity extends AppCompatActivity implements View.OnClickListener {

    private final int result = 1000;

    private EditText et_verification;
    private TextView tv_verification;
    private TextView tv_dialog_activity_sure;

    private String value = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_activity_verification);
        et_verification = (EditText) findViewById(R.id.et_verification);
        tv_verification = (TextView) findViewById(R.id.tv_verification);
        tv_dialog_activity_sure = (TextView) findViewById(R.id.tv_dialog_activity_sure);
        tv_verification.setOnClickListener(this);
        tv_dialog_activity_sure.setOnClickListener(this);

        getStringRandom(4);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_verification:
                getStringRandom(4);
                break;
            case R.id.tv_dialog_activity_sure:
                if (value.equalsIgnoreCase(et_verification.getText().toString())) {
                    setResult(result);
                    finish();
                } else {
                    Toast.makeText(DialogVerificationActivity.this, "验证码输入错误", Toast.LENGTH_SHORT).show();
                    getStringRandom(4);
                }
                break;
        }
    }

    //生成随机数字和字母,
    public void getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }

        value = val;
        tv_verification.setText(value);
    }
}
